package com.example.util.util;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class FileUtil {

    /*从第几行开始向上删除*/
    public static List<String> readAndRemoveFirstLines(File file, int lineNum) throws FileNotFoundException {
        List<String> strList = new ArrayList<String>();
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "rw");
            //Initial write position
            long writePosition = raf.getFilePointer();
            for (int i = 0; i < lineNum; i++) {
                String line = raf.readLine();
                if (line == null) {
                    break;
                }
                strList.add(line);
            }
            // Shift the next lines upwards.
            long readPosition = raf.getFilePointer();

            byte[] buff = new byte[1024];
            int n;
            while (-1 != (n = raf.read(buff))) {
                raf.seek(writePosition);
                raf.write(buff, 0, n);
                readPosition += n;
                writePosition += n;
                raf.seek(readPosition);
            }
            raf.setLength(writePosition);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return strList;
    }


    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static JSONObject readFileByLines(String fileName) {

        JSONObject jsonObject = new JSONObject();
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            long count = Files.lines(Paths.get(fileName)).count();
            log.info("文件名：{}存在{}行数据", fileName, count);
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                jsonObject.put(line + "", tempString);
                log.trace("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    log.error(e1.getMessage(), e1);
                }
            }
        }
        return jsonObject;
    }


    public static void put2File(String fileName, List<String> message, String fileWriterDir) {
        FileOutputStream fileOut = null;
        BufferedOutputStream bos = null;
        if (null == fileName || "".equals(fileName)) {
            log.info("fileName is empty!");
            return;
        }
        String path = null;
        if (StringUtils.isEmpty(fileWriterDir)) {
            path = System.getProperty("user.dir");
        } else {
            path = fileWriterDir;
            File file = new File(path);
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }
        }
        File file = new File(path + File.separator + fileName);
        try {
            fileOut = new FileOutputStream(file, true);
            bos = new BufferedOutputStream(fileOut);
            for (String line : message) {
                bos.write(line.getBytes("UTF-8"));
                bos.write(System.getProperty("line.separator").getBytes("UTF-8"));
            }
            bos.flush();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                bos.close();
                fileOut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void put2FileDelteOld(String fileName, List<String> message, String fileWriterDir) {
        FileOutputStream fileOut = null;
        BufferedOutputStream bos = null;
        if (null == fileName || "".equals(fileName)) {
            log.info("fileName is empty!");
            return;
        }
        String path = null;
        if (StringUtils.isEmpty(fileWriterDir)) {
            path = System.getProperty("user.dir");
        } else {
            path = fileWriterDir;
            File file = new File(path);
            if (!file.exists() && !file.isDirectory()) {
                file.mkdirs();
            }
        }
        File file = new File(path + File.separator + fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            fileOut = new FileOutputStream(file, true);
            bos = new BufferedOutputStream(fileOut);
            for (String line : message) {
                bos.write(line.getBytes("UTF-8"));
                bos.write(System.getProperty("line.separator").getBytes("UTF-8"));
            }
            bos.flush();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                bos.close();
                fileOut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void put2File(String message,String path) {
        FileOutputStream fileOut = null;
        BufferedOutputStream bos = null;
        File file = new File(path);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        File file2 = new File(path + File.separator + "error.txt");
        try {
            fileOut = new FileOutputStream(file2, true);
            bos = new BufferedOutputStream(fileOut);
            bos.write(message.getBytes("UTF-8"));
            bos.write(System.getProperty("line.separator").getBytes("UTF-8"));
            bos.flush();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                bos.close();
                fileOut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将一个文件夹下的文件按批次拆分
     *
     * @param path
     * @param path
     * @return
     */
    public static Boolean splitDirByTask(String path, Integer size, String name) {
        File file = new File(path);
        if (!file.exists() || !file.isDirectory()) {
            log.error("文件不存在或者不是文件夹");
            return Boolean.FALSE;
        }
        File[] files = file.listFiles();
        List<File> collect = Arrays.stream(files).sorted(Comparator.comparing(File::getAbsoluteFile)).filter(File::isFile).collect(Collectors.toList());
        int begin = 0;
        int end = 0;
        List<File> writeList = null;
        for (int i = 1; i <= size; i++) {
            begin = (i - 1) * 100;
            end = begin + 100;
            if (collect.size() < end) {
                end = collect.size();
            }
            writeList = collect.subList(begin, end);
            copyFile(writeList, name + i);
        }
        return Boolean.TRUE;
    }

    public static void copyFile(List<File> collect, String name) {
        try {
            File newpaths = null;
            File dirpaths = null;
            for (File file : collect) {
                String absolutePath = file.getAbsolutePath();
                String fileName = absolutePath.substring(absolutePath.lastIndexOf("/"));
                dirpaths = new File("/opt/app/rms_fg_sdwf/util-white/eight-mobile/task/" + name);
                if (!dirpaths.exists() && !dirpaths.isDirectory()) {
                    dirpaths.mkdirs();
                }
                newpaths = new File("/opt/app/rms_fg_sdwf/util-white/eight-mobile/task/" + name + "/" + fileName);
                if (!newpaths.exists()) {
                    Files.copy(file.toPath(), newpaths.toPath());
                    System.out.println("文件移动成功！起始路径：" + absolutePath);
                } else {
                    newpaths.delete();
                    Files.copy(file.toPath(), newpaths.toPath());
                    System.out.println("文件移动成功！起始路径：" + absolutePath);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
